<?php



class SiteController extends BaseController
{

    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex()
    {
    	$this->redirect(Yii::app()->homeUrl.'game/bomb');
        $now = date('H:i:s d-m-Y');

        $start = date('5:00:00 d-m-Y');
        $end = date('6:00:00 d-m-Y');
        $start = date('05:i:s d-m-Y');
        $end = date('06:i:s d-m-Y');
        if($now >= $start && $now < $end)
        {
        	//echo 'zzzz';
            $this->render('../game/khoagame');
        }
        else
        {
            $this->render('index');
        }
    }
    
    public function actionLoDe()
    {
    	$now = date('H:i:s d-m-Y');
    	$start = date('05:i:s d-m-Y');
    	$end = date('06:i:s d-m-Y');
    	
    	if($now >= $start && $now < $end )
    	{
    	
    		$this->render('../game/khoagame');
    	}
    	else
    	{
    		
    		$this->render('index');
    	}
    } 
    public function actionkhoagame(){
    	$this->render('../game/khoagame');
    }
    public function actionthongkelode(){

    	$lokhan = Lokhan::model()->findAll();
    	$data=array();
    		foreach ($lokhan as $dauso){
    			$set=array();
    			$set['value']=$dauso->value;
    			$set['days']=$dauso->days;
    			$set['max_khan']=$dauso->max_khan;
    			$data[]=$set;
    			//echo $dauso->value.'--'.$dauso->days.'--'.$dauso->max_khan.'<br/>';
    		}
    	
    		function cmp($a,$b){
    			if ($a['days']==$b['days'])
    				return 0;
    			return ($a['days']<$b['days']) ? 1 : -1;
   		 	}
    	usort($data,"cmp");
    	$this->render('thongkelode',array('data'=>$data));
    	//foreach ($data as $e)
    	//	echo $e['value'].'--'.$e['days'].'--'.$e['max_khan'].'<br/>';
    }
    

    public function actionMostchoosen(){

		$this->render('mostchoosen');
    }

    public function actionshowwithdraw()
    {
		$wdlist=Yii::app()->db->createcommand(
				'select b.user_name,a.* from ld_withdraw a left join
				 ld_user b 
on a.user_id=b.user_id
order by serialno desc limit 0,7'
				)->queryAll();
		
		$this->renderpartial('listwithdraw',array('list'=>$wdlist));
    }
    
    public function actionlistallwithdraw()
    {
    	$page=isset($_GET['page']) ? $_GET['page'] : 1;
    	
		$sql="select  b.user_name,a.* from ld_withdraw a left join
    			ld_user b
    			on a.user_id=b.user_id 
    			where send_date>'".date('Y-m-d H:i:s',strtotime(" +14 hours - 800 days"))."'
    			 order by serialno desc LIMIT ".(($page-1)*20).",20";
    	$wdlist=Yii::app()->db->createcommand($sql)->queryAll();
    	//echo $sql;
    	
    	$maxpage=Yii::app()->db->createcommand(
    			"select count(*) as num from ld_withdraw  where send_date 
    			>'".date('Y-m-d H:i:s',strtotime(" +14 hours - 400 days"))."'")->queryscalar();
		$maxpage=($maxpage-$maxpage%20)/20+1;
    	
    	$this->render('listallwithdraw',array('list'=>$wdlist,'len'=>$maxpage));
    }    
    
    public function actionshowdeposit()
    {
    	$wdlist=Yii::app()->db->createcommand(
    			'select b.user_name,a.* from ld_deposit_history a left join
    			ld_user b
    			on a.user_id=b.user_id
    			order by serialno desc limit 0,7'
    	)->queryAll();
    
    	$this->renderpartial('listdeposit',array('list'=>$wdlist));
    }
    
    public function actionlistalldeposit()
    {
    	$page=isset($_GET['page']) ? $_GET['page'] : 1;
    	 
    
    	$wdlist=Yii::app()->db->createcommand(
    			"select  b.user_name,a.* from ld_deposit_history a left join
    			ld_user b
    			on a.user_id=b.user_id where deposit_date >
    			'".date('Y-m-d H:i:s',strtotime(" +14 hours - 800 days"))."'
    			order by serialno desc LIMIT ".(($page-1)*20).",20"
    	)->queryAll();
    	 
    	$maxpage=Yii::app()->db->createcommand(
    			"select count(*) as num from 
    			ld_deposit_history where deposit_date 
    			>'".date('Y-m-d H:i:s',strtotime(" +14 hours - 400 days"))."'")->queryscalar();
    	$maxpage=($maxpage-$maxpage%20)/20+1;
    	 
    	$this->render('listalldeposit',array('list'=>$wdlist,'len'=>$maxpage));
    }    
    
    

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        if ($error = Yii::app()->errorHandler->error)
        {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }
    
    //Lien he
    public function actionContact()
    {
    	// using the default layout 'protected/views/layouts/main.php'
    	$this->renderPartial('lienhe');
    }

    
    public function actionshowmoney()
    {
    	$libertyAPI = new LibertAPIWrapper();
    	$response = $libertyAPI->showmoney('usd');
    	$money = Yii::app()->db->createcommand("SELECT total_money from ld_total_money")->queryscalar();
    	$money += (float)$response[0];
    	echo '<span style="font-size:12px;font-family:arial;">Tài khoản LR của chúng tôi hiện còn : '.$money." USD</span>";
    }    
    
    //hoi dap
    public function actionGioithieukiemtien()
    {
    	// using the default layout 'protected/views/layouts/main.php'
    	$data = array();
    	$setting = Yii::app()->db->createCommand()
					    	->select('*')
					    	->from('ld_news')
					    	->where('id=:v', array(':v'=>'2'))
					    	->queryRow();
    	$data['rule'] = $setting['content'];
    	$this->render('gioithieukiemtien', $data);
    }
    //huongdan
    public function actionHuongdan()
    {
    	// using the default layout 'protected/views/layouts/main.php'
    	$data = array();
    	$setting = Yii::app()->db->createCommand()
						    	->select('*')
						    	->from('ld_news')
						    	->where('id=:v', array(':v'=>'1'))
						    	->queryRow();
    	$data['rule'] = $setting['content'];
    	$this->render('huongdan', $data);
    }
    //luat choi
    public function actionLuatchoi()
    {
    	// using the default layout 'protected/views/layouts/main.php'
    	$data = array();
    	$setting = Yii::app()->db->createCommand()
    							->select('*')
    							->from('ld_news')
    							->where('id=:v', array(':v'=>'3'))
    							->queryRow();
    	$data['rule'] = $setting['content'];
    	$this->render('luatchoi', $data);
    }

    public function actionRegister()
    {
        $model = new RegisterForm();
        if (isset($_POST['RegisterForm']))
        {
            $model->attributes = $_POST['RegisterForm'];
            $user_Model = new User;
           // $user_Model->your_name = $_POST['RegisterForm']['your_name'];
            $user_Model->user_name = $_POST['RegisterForm']['user_name'];
            $user_Model->password = md5($_POST['RegisterForm']['password']);
            $user_Model->email = $_POST['RegisterForm']['email'];
            $user_Model->lr_acc = $_POST['RegisterForm']['lr_acc'];
            $user_Model->phone = $_POST['RegisterForm']['phone'];
            $user_Model->date_reg = date('Y-m-d H:i:s');
            
            $default_ref_id=isset(Yii::app()->request->cookies['ref_id']->value) ?
            (Yii::app()->request->cookies['ref_id']->value) : '1';  
           // $user_Model->id_ref=$default_ref_id; 
            
            if ($model->validate() && $user_Model->save())
            {
            //	echo 'LLLLLLLLLLLLLLL'.$user_Model->user_id;
            	$ref_user = User::model()->find('user_id=:user_id',
            			array(':user_id'=>$default_ref_id));
            	//echo 'LLLLLLLLLLLLLLL'.$_POST['RegisterForm']['ref_id'];
            	$array_child = $ref_user->ref_id;
            	$array_child.=",".$user_Model->user_id;
            	//echo 'ARRRRRRRRRRRRRRRR'.$array_child;
            	$ref_user->ref_id=$array_child;
            	$ref_user->save();
                 // send welcome mail
                $mailUtil = new MailUtil();
                $mailUtil->sendWelcomeMail($user_Model);
               // $mailUtil->sendActiveMail($user_Model);
                // Sau khi Ä‘Äƒng kÃ­ thÃ nh cÃ´ng thÃ¬ login luÃ´n
//                $model = new LoginForm();
//                $model->username = $_POST['RegisterForm']['user_name'];
//                $model->password = $_POST['RegisterForm']['password'];
//                if ($model->validate() && $model->login())
//                {
//                    $this->redirect('index');
//                }
                // Sau khi Ä‘Äƒng kÃ­ thÃ nh cÃ´ng thÃ¬ hiá»‡n thÃ´ng bÃ¡o yÃªu cáº§u kÃ­ch hoáº¡t
                $this->render('register_success');
                return;
            }
        }
        $this->render('register', array('model' => $model));
    }
    
    public function actionPartialLogin()
    {
    	// Náº¿u Ä‘Äƒng nháº­p rá»“i thÃ¬ ko cáº§n ná»¯a
    	if(!Yii::app()->user->isGuest)
    	{
    		$this->redirect(Yii::app()->homeUrl);
    	}
    	$model = new LoginForm();
    
    	// collect user input data
    	if (isset($_POST['LoginForm']))
    	{
    		$model->attributes = $_POST['LoginForm'];
    		 
    		// validate user input and redirect to the previous page if valid
    		if ($model->validate() && $model->login())
    		{
    			$this->redirect(Yii::app()->user->returnUrl);
    		}
    		$this->redirect(Yii::app()->user->returnUrl);
    	}
    	
    	// display the login form
    	$this->renderPartial('login', array('model' => $model));
    }
    
    public function actionLogin()
    {
        // Náº¿u Ä‘Äƒng nháº­p rá»“i thÃ¬ ko cáº§n ná»¯a
        if(!Yii::app()->user->isGuest)
        {
            $this->redirect(Yii::app()->homeUrl);
        }
        $model = new LoginForm();

        // collect user input data
        if (isset($_POST['LoginForm']))
        {
            $model->attributes = $_POST['LoginForm'];
   
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
            {
                $this->redirect(Yii::app()->user->returnUrl);
            }
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout()
    {
        Yii::app()->user->logout();
        // clear session
        Yii::app()->session->destroy();
        $this->redirect(Yii::app()->homeUrl);
    }
    
    public function actiontest()
    {
    	echo 'dcm';
    $mail = new PHPMailer();  // tạo một đối tượng mới từ class PHPMailer
    $mail->IsSMTP(); // bật chức năng SMTP
    $mail->SMTPDebug = 0;  // kiểm tra lỗi : 1 là  hiển thị lỗi và thông báo cho ta biết, 2 = chỉ thông báo lỗi
    $mail->SMTPAuth = true;  // bật chức năng đăng nhập vào SMTP này
    $mail->SMTPSecure = 'ssl'; // sử dụng giao thức SSL vì gmail bắt buộc dùng cái này
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 465; 
    $mail->Username = 'lexuanminhhoang@gmail.com';  
    $mail->Password = 'L@ngnh4ng';           
    $mail->SetFrom('vietlode@gmail.com', 'nguoi gui');
    $mail->Subject = 'test subject';
    $mail->Body = 'body';
    $mail->AddAddress('gohanvn@gmail.com');
    if(!$mail->Send()) {
        $error = 'Gởi mail bị lỗi: '.$mail->ErrorInfo; 
        echo $error;
       
    } else {
        $error = 'thư của bạn đã được gởi đi ';echo $error;
      
    }
    exit;
    }

    public function actionLostPassword()
    {
        $model = new LostPassForm();
        if(isset ($_POST['LostPassForm']))
        {
            $model->setAttributes($_POST['LostPassForm']);
            if($model->validate())
            {
                $user = User::model()->find('email = :email', array(':email'=>$model->email));
                if(!$user)
                {
                    $model->addError('email', 'Không có user nào đăng ký dùng email này. Xin thử lại ');
                }
                else
                {
                    $mailUtil = new MailUtil();
                    if($mailUtil->sendResetMail($user))
                    {
                        $this->render('lostpass_success');
                    }
                }
            }
        }
        $this->render('lost_password', array('model'=>$model));
    }
    
    public function actionLayDanhSachPhongThan()
    {
        $lstPhongThan = LoDe::layDanhSach10PhongThan();
        $this->renderPartial('phong_than', array('lstPhongThan'=>$lstPhongThan));
    }
    
    public function actionfullphongthan()
    {
    	
    	$page=isset($_GET['page']) ? $_GET['page'] : 1;

    	
    	$wdlist=Yii::app()->db->createcommand(
    			'SELECT a.*, b.lode_type_name, c.user_name as player_name
    	FROM ld_lode a join ld_lode_type b on a.lode_type = b.lode_type_id join ld_user c 
    			on a.player_id = c.user_id
    	WHERE a.win_money > 0
    	ORDER BY a.play_date DESC, a.win_money DESC LIMIT '.(($page-1)*20).',20'
    	)->queryAll();
    	
    	$maxpage=Yii::app()->db->createcommand(
    			'select count(*) as num from ld_lode where win_money>0')->queryscalar();
    	$maxpage=($maxpage-$maxpage%20)/20+1;
    	
    	$this->render('fullphong_than',array('list'=>$wdlist,'len'=>$maxpage));
    	
    	
  
    }
    
    
    public function actionNewDetail()
    {
        $thong_bao = Yii::app()->db->createCommand()
                                        ->select('*')
                                        ->from('ld_news')
                                        ->where('id=:v', array(':v' => '4'))
                                        ->queryRow();
        $this->layout = '/layouts/main';
        $this->render('thong_bao', array('new_content'=>$thong_bao['content']));
    }
    
    public function actionXemKetQuaXoSo()
    {
        $ketquaxs = Ketquaxoso::model()->findBySql("SELECT DATE_FORMAT(a.date,'%d/%m/%Y') as date, a.x80, a.x8, a.x3dot5 FROM ld_ketquaxoso a ORDER BY a.date DESC LIMIT 0,1");
        $this->render('ketqua_xoso', array('model' => $ketquaxs));
    }
    
    public function actionAjaxXemKetQuaXoSo()
    {
        $date = (isset($_GET['view_date']) && $_GET['view_date'] !== '') ? $_GET['view_date'] : date('Y-m-d');
        //exit($date);
        $ketquaxs = Ketquaxoso::model()->findBySql("SELECT DATE_FORMAT(a.date,'%d/%m/%Y') as date, a.x80, a.x8, a.x3dot5 FROM ld_ketquaxoso a  WHERE a.date = '$date' ORDER BY a.date DESC LIMIT 0,1");
        //var_dump($ketquaxs);
        if($ketquaxs)
        {
            $this->renderPartial('ketqua_xoso_ajax', array('model' => $ketquaxs));
        }
        else
        {
            echo '<strong>Không có kết quả xổ số cho ngày '.$date.'</strong>';
        }
    }
}